<template>
  <van-form class="order-add" @submit="onSubmit">
    <van-field v-model="addForm.orderId" label="工单ID" required readonly />
    <van-field class="direction"
      v-model="addForm.orderName" label="工单标题" placeholder="请输入工单标题"
      required :rules="[{ required: true, message: '请输入工单标题' }]"
    />
    <van-field
      v-model="addForm.planFinishTime" label="期望时间" required
      @click="isShowPlanFinish = true"
    />
    <van-calendar color="#1989fa" v-model="isShowPlanFinish" @confirm="confirmPlanFinish" />
    <van-field readonly clickable v-model="orderTypeName"
      required :rules="[{ required: true, message: '请点击选择工单类型' }]"
      label="工单类型" placeholder="点击选择工单类型" @click="isShowOrder = true"
    />
    <van-popup v-model="isShowOrder" position="bottom">
      <van-picker
        show-toolbar value-key="name" title="工单类型"
        :columns="orderList" @confirm="confirmOrder" @cancel="isShowOrder = false"
      />
    </van-popup>
    <van-field readonly clickable v-model="serviceKindName"
      required :rules="[{ required: true, message: '请点击选择业务类型' }]"
      label="业务类型" placeholder="点击选择业务类型" @click="isShowService = true"
    />
    <van-popup v-model="isShowService" position="bottom">
      <van-picker
        show-toolbar value-key="name" title="业务类型"
        :columns="serviceList" @confirm="confirmService" @cancel="isShowService = false"
      />
    </van-popup>
    <van-field readonly clickable v-model="serviceNextName"
      required :rules="[{ required: true, message: '请点击选择二级业务类型' }]"
      label="二级业务类型" placeholder="点击选择二级业务类型" @click="isShowServiceNext = true"
    />
    <van-popup v-model="isShowServiceNext" position="bottom">
      <van-picker
        show-toolbar value-key="serviceNextName" title="二级业务类型"
        :columns="serviceNextList" @confirm="confirmServiceNext" @cancel="isShowServiceNext = false"
      />
    </van-popup>
    <van-field class="direction" required name="radio" label="中台类型">
      <template #input>
        <van-radio-group v-model="addForm.marketType" direction="horizontal">
          <van-radio name="01" icon-size="16px">公众中台</van-radio>
          <van-radio name="02" icon-size="16px">政企中台</van-radio>
          <van-radio name="03" icon-size="16px">网络中台</van-radio>
        </van-radio-group>
      </template>
    </van-field>
    <van-field class="direction" v-model="addForm.orderContent" label="工单内容" rows="2" autosize
      placeholder="请输入详情内容，方便我们快速处理问题" type="textarea"
      maxlength="200" show-word-limit 
      required :rules="[{ required: true, message: '请输入工单内容' }]"
    />
    <van-field class="direction" label="附件上传">
      <template #input>
        <van-uploader v-model="fileList"
          accept=".jpg,.png,.doc,.docx,.pdf,.zip,.txt,.xls,.xlsx"
          :before-read="beforeRead"
          :after-read="(file) => afterUpload(file)"
          :before-delete="beforeDelete"
        />
      </template>
    </van-field>
    <div class="order-save">
      <van-button type="warning" text="暂存" native-type="button" @click="dealSubmit" />
      <van-button type="info" text="创建" native-type="submit" />
    </div>
  </van-form>
</template>

<script>
import * as dayjs from "dayjs"
import { Dialog, Toast } from 'vant'
import { userInfo, orderTypeList, serviceKindList, serviceKindNameList, uploadFile, delUpload, addSave } from '@/api/order.js'

export default {
  data() {
    return {
      userInfo: {
        catcherDeptId: '',
        createrPostId: '',
        createrPostName: '',
        createrDeptName: '',
        catcherName: '',
        createrPhone: '',
        areaNo: '',
        areaName: '',
        catcherLogin: ''
      },
      addForm: {
        orderId: new Date().toLocaleString().replaceAll('/', '').replaceAll(':', '').replace(/\s*/g,''),
        orderName: '',
        planFinishTime: dayjs(new Date()).format('YYYY-MM-DD'),
        orderType: '',
        flowId: '',
        serviceKind: '',
        serviceNextKind: '',
        marketType: '01',
        orderContent: ''
      },
      orderTypeName: '',
      serviceKindName: '',
      serviceNextName: '',
      isShowPlanFinish: false,
      isShowOrder: false,
      orderList: [], // 工单类型
      isShowService: false,
      serviceList: [], // 业务类型
      isShowServiceNext: false,
      serviceNextList: [], // 二级业务类型 
      fileList: []
    }
  },
  mounted() {
    this.getUserInfo()
    this.getOrderTypeList()
  },
  beforeDestroy() {
    Toast.clear()
  },
  methods: {
    async getUserInfo() {
      const res = await userInfo({})
      const { result, success } = res
      if (success) {
        this.userInfo.catcherDeptId = result.orgCode
        this.userInfo.createrPostId = result.postId
        this.userInfo.createrPostName = result.postFamily
        this.userInfo.createrDeptName = result.orgName
        this.userInfo.catcherName = result.staffName
        this.userInfo.createrPhone = result.mobile
        this.userInfo.areaNo = result.areaNo
        this.userInfo.areaName = result.areaName
        this.userInfo.catcherLogin = result.accountCode
      }
    },
    // 选择期望时间
    confirmPlanFinish(date) {
      this.isShowPlanFinish = false
      this.addForm.planFinishTime = dayjs(date).format('YYYY-MM-DD')
    },
    // 选择工单类型popup
    confirmOrder(val) {
      this.isShowOrder = false
      this.addForm.orderType = val.id
      this.addForm.flowId = val.flowId
      this.orderTypeName = val.name
      this.addForm.serviceKind = ''
      this.serviceKindName = ''
      this.addForm.serviceNextKind = ''
      this.serviceNextName = ''
      this.getServiceKindList(this.addForm.orderType)
    },
    // 工单类型数据
    async getOrderTypeList() {
      const res = await orderTypeList({})
      const { result, success } = res
      if (success) {
        this.orderList = result
      }
    },
    // 选择业务类型popup
    confirmService(val) {
      this.isShowService = false
      this.addForm.serviceKind = val.id
      this.serviceKindName = val.name
      this.addForm.serviceNextKind = ''
      this.serviceNextName = ''
      this.getServiceKindNameList(this.addForm.serviceKind)
    },
    // 业务类型数据
    async getServiceKindList(orderType) {
      const res = await serviceKindList({ orderType })
      const { result, success } = res
      if (success) {
        this.serviceList = result
      }
    },
    // 选择二级业务类型popup
    confirmServiceNext(val) {
      this.isShowServiceNext = false
      this.addForm.serviceNextKind = val.serviceNextKind
      this.serviceNextName = val.serviceNextName
    },
    // 二级业务类型数据
    async getServiceKindNameList(serviceKind) {
      const res = await serviceKindNameList({ serviceKind })
      const { result, success } = res
      if (success) {
        this.serviceNextList = result
      }
    },
    // 上传附件检验
    beforeRead(file) {
      const isFileType = file.type === 'image/jpeg' || file.type === 'image/png'
          || file.type === 'application/msword' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
          || file.type === 'application/pdf'
          || file.type === 'text/plain'
          || file.type === 'application/zip'
          || file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isFileType) {
        Toast('请上传.jpg,.png,.doc,.docx,.pdf,.zip,.txt,.xls,.xlsx格式的文件或图片')
      }
      return isFileType
    },
    // 删除
    async beforeDelete(file) {
      const res = await delUpload({ fileName: file.url, orderId: this.addForm.orderId })
      const { success, message } = res
      if(success) { 
        return true
      } else {
        Dialog.alert({ message })
        return false
      }
    },
    // 上传
    async afterUpload(file) {
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('orderId', this.addForm.orderId)
      const res = await uploadFile(formData)
      const { message, success, result } = res
      if(success) {
        file.url = result
        file.status = 'success'
        file.message = '上传成功'
      } else {
        file.status = 'failed'
        file.message = message
      }
    },
    // 提交
    onSubmit() {
      Dialog.confirm({
        message: '确定创建工单？',
      })
      .then(() => {
        Toast({
          type:'loading',
          duration: 0,
          message: '保存中...',
          position: 'bottom',
          forbidClick: 'true'
        })
        this.saveAddInfo()
      })
      .catch(() => {
        
      })
    },
    // 创建
    async saveAddInfo() {
      const res = await addSave({ ...this.addForm, ...this.userInfo, orderStatus: '1' })
      const { success, message } = res
      if(success) {
        this.$open.call(this, '/order/overview')
      } else {
        Dialog.alert({ message })
      }
    },
    dealSubmit() {
      Dialog.confirm({
        message: '确定暂存工单？',
      })
      .then(() => {
        Toast({
          type:'loading',
          duration: 0,
          message: '保存中...',
          position: 'bottom',
          forbidClick: 'true'
        })
        this.saveDraftInfo()
      })
      .catch(() => {
        
      })
    },
    // 草稿
    async saveDraftInfo() {
      const res = await addSave({ ...this.addForm, ...this.userInfo, orderStatus: '0' })
      const { success, message } = res
      if(success) {
        this.$open.call(this, '/order/overview')
      } else {
        Dialog.alert({ message })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.order-add {
  /deep/ .van-cell {
    margin-bottom: 8px;
    padding: 10px 24px;
    &::after {
      content: none;
    }
    .van-field__control {
      text-align: right;
    }
    .van-field__error-message {
      text-align: right;
    }
    &.direction {
      flex-direction: column;
      .van-field__control {
        text-align: left;
      }
      .van-field__error-message {
        text-align: left;
      }
    }
  }
  .van-cell--required::before {
    left: 14px;
  }
  /deep/ .van-field--error .van-field__control::placeholder {
    color: #969799;
  }
  .order-save {
    display: flex;
    justify-content: space-around;
    .van-button {
      width: 40%;
    }
  }
}
</style>
